<?php 
namespace Dershun\RealNameAuthentication;
use Dershun\RealNameAuthentication\Encryption;

/**
* 接口调用方法
*/
class Authentication extends Encryption
{
	
	private $type;//调用接口类型
	private $http = "http";//通信协议
	private $messageData = [];//报文明文数据 

	public function __construct()
	{	
		parent::__construct();
	}

	/**
	 * 外部调用接口
	 * @param  [type] $type 调用接口类型 1、实名接口：check 2、实名查询接口：query 3、行为上报：loginout
	 * 
	 * @param  [type] $data 报文明文数据 
	 *                      数据结构：	check：		{"ai":"游戏内部成员标识","name":"用户姓名","idNum":"用户身份证号码"}  
	 *                      			query：		{"ai":"游戏内部成员标识"}  
	 *                         			loginout：	{"collections":[{"no":编号1-128,"si":"游戏内部会话标识（同一用户单次游戏会话中，上下线动作必须使用同一会话标识上报）","bt":0下线1上线,"ot":行为发生时间戳（秒）,"ct":0已认证通过2游客用户,"di":"游客模式设备标识(ct为2必填)","pi":"实名认证用户的唯一标识(ct为0必填)"}]}
	 *                         			
	 * @return [type]       [description]
	 */
	public function authentication($type,$data){

		if(empty($data)){
			$this->setError(101,"缺少报文数据");
			return false;
		}

		$this->messageData = $data;
		$this->type = $type;

		if($type == "check"){

			$redata = $this->postInterface();

		}else if($type == "query"){

			$redata = $this->getInterface();

		}else if($type == "loginout"){

			$redata = $this->postInterface();

		}else{
			$this->setError(104,"调用接口类型不合法");
			return false;
		}
		
		if(empty($redata)) {
			// $this->setError(109,"接口访问失败！");
			return false;
		}

		$redata = json_decode($redata,true);

		$redata['errorexplain'] = $this->errorMsg[$redata['errcode']]['errorexplain'];//获取错误说明

		return $redata;
	}

	/**
	 * 接口测试
	 * @param  [type] $type 测试接口类型
	 * @param  [type] $code 测试码
	 * @param  [type] $data 测试数据
	 * @return [type]       [description]
	 */
	public function testInterface($type,$code,$data){
		if(empty($type)){
			$this->setError(101,"缺少接口类型type");
			return false;
		}

		if(empty($code)){
			$this->setError(101,"缺少测试码code");
			return false;
		}

		if(empty($data)){
			$this->setError(101,"缺少报文数据data");
			return false;
		}

		$Message = $this->encryptedMessage($data);//加密后的数据
		$Signdata = [];
		$postdata = ["data"=>$Message];

		if($type == "checkUrlTest"){
			$url = "https://wlc.nppa.gov.cn/test/authentication/check"."/".$code;
		}else if($type == "queryUrlTest"){
			$url = "https://wlc.nppa.gov.cn/test/authentication/query"."/".$code."?ai=".$data['ai'];
			$Signdata = $data;
			$postdata = [];
		}else if($type == "loginoutUrlTest"){
			$url = "https://wlc.nppa.gov.cn/test/collection/loginout"."/".$code;
		}else{
			$this->setError(101,"缺少接口类型错误");
			return false;
		}

		$this->getSign($Signdata);//签名

		$data = $this->curlApplication($url,$postdata);
		return json_decode($data,true);
	}

	/**
	 * GET接口调用
	 * @param  [type] $data 报文数据 
	 * @return [type]       [description]
	 */
	private function getInterface(){

		$Message = $this->encryptedMessage($this->messageData);//加密后的数据
		if(empty($Message)) return false;

		$getSign = $this->getSign($this->messageData);//签名
		if(empty($getSign)) return false;

		$data = $this->curlApplication($this->config[$this->type.'Url']."?ai=".$this->messageData['ai']);

		return $data;

	}

	/**
	 * POST接口调用
	 * @param  [type] $data 报文数据 {"ai":"游戏内部成员标识","name":"用户姓名","idNum":"用户身份证号码"}
	 * @return [type]       [description]
	 */
	private function postInterface(){

		$Message = $this->encryptedMessage($this->messageData);//加密后的数据
		if(empty($Message)) return false;

		$getSign = $this->getSign();//签名
		if(empty($getSign)) return false;

		$postdata = ["data"=>$Message];

		$data = $this->curlApplication($this->config[$this->type.'Url'],$postdata);

		return $data;

	}

	/**
	 * curl应用
	 * @param  [type] $url      请求地址
	 * @param  [type] $protocol 通信协议 http\https
	 * @param  [type] $postdata post数据
	 * @return [type]           返回数据
	 */
	private function curlApplication($url,$postdata=array()){

		$header = array(
            'Content-Type: application/json; charset=utf-8',
            'appId: '.$this->config['appId'].'',
            'bizId: '.$this->config['bizId'].'',
            'timestamps: '.$this->msectime.'',
            'sign: '.$this->Sign.''
        );

        $method = "GET";
		
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        if(!empty($postdata)){
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
            $method = "POST";
            $header[] = 'Expect:';
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名

        if(strpos($url,"https") !== false){
            curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , FALSE );//https 请求
            curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST , FALSE );//https 请求
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        $data = curl_exec($ch);
        if (curl_errno($ch) != 0) {
            $message = "Server request failed: " . curl_error($ch);
            $this->setError(400,$message);
        }

        curl_close($ch);//关闭curl

	    return $data;
	}

}